package pay

import (
	"errors"
	"fmt"
	"go_payment/app/library/notify"
	"go_payment/app/param_model"
	"go_payment/app/utils"
	"go_payment/dao"
	"go_payment/model"
	"time"
)

type Base struct {
}

func (this *Base) AddOrder(trade param_model.Trade) (*AddOrderDTO, error) {
	if trade.MerchantId == 0 {
		return nil, errors.New("数据错误")
	}
	//用户基本信息校验
	member := dao.GetMemberInfoById(trade.GetMemberId())
	if member.ID == 0 {
		return nil, errors.New("API商户不存在")
	}
	if member.Status != 1 {
		return nil, errors.New("商户API未激活")
	}
	if member.Authorized != 1 {
		return nil, errors.New("商户api未认证")
	}
	if member.Apikey == "" {
		return nil, errors.New("商户api密匙未分配")
	}
	// 签名校验
	authed := utils.AuthSign(trade, member.Apikey)
	if authed == false {
		return nil, errors.New("签名不正确")
	}
	// 获取用户在对应渠道下的账户配置信息
	channel := dao.GetChannelInfoById(trade.GetChannelId())
	if channel.Id == 0 {
		return nil, errors.New("渠道信息不正确")
	}
	configs := dao.GetProductUserConf(trade.GetMemberId(), channel.BankId, trade)

	if len(configs) == 0 {
		return nil, errors.New("账户信息未配置或全关停!")
	}
	//todo这边不做多配置轮询，直接选第一个配置
	userConf := configs[0]
	// 订单信息入库
	var order model.Order
	order.OrderId = utils.GenSystemOrderId(trade.MerchantId)
	order.MchId = trade.MerchantId
	order.Amount = trade.Amount
	order.Poundage = 0
	order.PreAmount = 0
	order.ActualAmount = 0
	order.ApplyDate = time.Now().Unix()
	order.BankCode = fmt.Sprint(trade.BankCode)
	order.BankName = ""
	order.NotifyUrl = trade.NotifyUrl
	order.CallBackUrl = trade.CallbackUrl
	order.Status = 0
	order.TongDao = channel.Code
	order.TongDaoZh = channel.Title
	order.TJUrl = ""
	order.Attach = trade.Attach
	order.OutTradeId = trade.OrderId
	order.MemberId = userConf.MchID
	order.Key = userConf.SignKey
	order.AppId = userConf.AppId
	order.AppSecret = userConf.AppSecret

	_, err := dao.AddOrder(&order)
	if err != nil {
		return nil, err
	}

	dto := new(AddOrderDTO)
	dto.AppId = userConf.AppId
	dto.OrderId = order.OrderId
	dto.AppSecret = userConf.AppSecret
	return dto, nil
}

func (this *Base) HandlerOrder(orderSn string) error {
	//1.获取订单信息
	order := dao.GetOrder(orderSn)
	if order.OrderId == "" {
		return errors.New("订单信息不存在")
	}
	//2.通知用户
	err := this.NotifyUser(order)
	return err
}

func (this *Base) NotifyUser(order model.Order) error {
	url := order.NotifyUrl
	obj := notify.NewNotify(url)
	err := obj.DoNotify()
	return err
}

type AddOrderDTO struct {
	MchId     string //商户号
	SignKey   string //密钥
	AppId     string
	AppSecret string
	OrderId   string
}

type DTO struct {
	OrderSn     string
	TransId     string
	QrCode      string
	H5Url       string
	AppData     string
	WxUrlScheme string
	WxPay       string
}
